package com.li.netty.serve;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 11/16/2022 8:54 AM
 */
@Component
public class SocketServer {

    private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);

    /**
     * 负责初始化 netty 服务器
     */
    private ServerBootstrap serverBootstrap;

    @Autowired
    private SocketInitializer socketInitializer;

    @Value("${netty.websocket.port}")
    private int port;

    /**
     * 启动 netty 服务器
     */
    public void start() {
        this.init();
        this.serverBootstrap.bind(this.port);
        logger.info("Netty started on port: {} (TCP) with boss thread {}", this.port, 2);
    }

    /**
     * 初始化 netty 配置
     */
    private void init() {
        // 创建两个线程组 bossGroup 为接收请求的线程组 一般1-2个就行
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        // 实际工作的线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        // 两个线程组加入进来 加入自己的初始化器
        this.serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(this.socketInitializer);
    }
}